﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NServiceKit.Common.Extensions;

namespace RoyEngine
{

    //internal class RoyCache
    //{
    //    private readonly Dictionary<string, RoyDataImage> _images = new Dictionary<string, RoyDataImage>();

    //    internal RoyDataImage Get(RoyDataBase entity)
    //    {
    //        string key = entity.GetType().Name + ":" + entity.Id;
    //        lock (_images)
    //        {
    //            RoyDataImage image;
    //            if (_images.TryGetValue(key, out image))
    //            {
    //                _images.Remove(key);
    //            }
    //            return image;
    //        }
    //    }

    //    internal void Set(RoyDataBase entity)
    //    {
    //        lock (_images)
    //        {
    //            string key = entity.GetType().Name + ":" + entity.Id;
    //            _images[key] = entity;
    //        }
    //    }

    //    internal void Clear()
    //    {
    //        lock (_images)
    //        {
    //            _images.Clear();
    //        }
    //    }
    //}


    class RoyCache
    {
        public string Id { get; set; }

        private Dictionary<string, object> Properties = new Dictionary<string, object>();


        public static implicit operator RoyCache(RoyDataBase entity)
        {
            RoyCache cache = new RoyCache();

            cache.Id = entity.Id;
            var info = Roy.GetRoyDataInfo(entity);

            foreach (var valueInfo in info.HashPropertiesInfo.Properties)
            {
                cache.Properties.Add(valueInfo.PropertyInfo.Name, valueInfo.PropertyInfo.GetValue(entity));
            }

            foreach (var valueInfo in info.ListPropertiesInfo)
            {
                switch (valueInfo.InnerType)
                {
                    case ValueType.Boolean:
                        cache.Properties.Add(valueInfo.PropertyInfo.Name, (valueInfo.PropertyInfo.GetValue(entity) as List<bool>).ToList());
                        break;
                    case ValueType.Int32:
                        cache.Properties.Add(valueInfo.PropertyInfo.Name, (valueInfo.PropertyInfo.GetValue(entity) as List<int>).ToList());
                        break;
                    case ValueType.Int64:
                        cache.Properties.Add(valueInfo.PropertyInfo.Name, (valueInfo.PropertyInfo.GetValue(entity) as List<long>).ToList());
                        break;
                    case ValueType.String:
                        cache.Properties.Add(valueInfo.PropertyInfo.Name, (valueInfo.PropertyInfo.GetValue(entity) as List<string>).ToList());
                        break;
                }
            }

            return cache;
        }

        public object this[string propertyName]
        {
            get { return Properties[propertyName]; }
        }
    }
}
